package com.xxx.registry;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created by louisyuu on 2020/4/29 上午10:54
 */
public class ZkUtils {

    private final static String DEFAULT_CONNECT_ADDRESS = "127.0.0.1:2181";

    private final static String DEFAULT_NAMESPACE = "servers";

    private static CuratorFramework globalZkClient;


    private ZkUtils() {
    }

    public static CuratorFramework getZkClient() {
        return globalZkClient;
    }


    static {
        initGlobalZkClient();
    }


    private static void initGlobalZkClient() {
        globalZkClient = createSession(DEFAULT_CONNECT_ADDRESS, DEFAULT_NAMESPACE);
    }


    public static CuratorFramework createSession(String connectAddress, String namespace) {
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(connectAddress)
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace(namespace)  // 独立的命名空间 /base
                .build();

        client.start();
        return client;


    }


}
